package service.orcService;

import model.Blocks;
import model.MyRect;
import model.TextBlock;
import net.sourceforge.tess4j.ITessAPI;
import net.sourceforge.tess4j.TessAPI;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.Word;
import orc.Img;
import orc.TessRactFactory;
import org.slf4j.LoggerFactory;
import service.outputDocument.DocumentCreator;
import util.FileUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by wrh on 17-9-30.
 */
public class OrcServiceImpl implements OrcService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(OrcService.class);

    /**
     * 将接受到的图像字节数组处理识别后,返回生成的doc文档
     * @param imgBytes 图像字节数组
     * @return
     */
    public byte[] getDoc(byte[] imgBytes) throws IOException {

        //解码数据
        BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(imgBytes));
        //处理图像
        Img img = new Img(bufferedImage);
        img.gray2BinaryByKernel();

        String date=new SimpleDateFormat("yyyymmddHHMMSS").format(new Date());
        //创建文件夹
        File tomcatPath=new File(OrcServiceImpl.class.getResource("/").getPath()).getParentFile();
        File outPutDocDir = new File(tomcatPath.getAbsolutePath()+"/"+"outPutDir");
        if (!outPutDocDir.exists() || !outPutDocDir.isDirectory()){
            outPutDocDir.mkdir();
        }
        logger.info("文件保存路径"+outPutDocDir.getAbsolutePath());

        //获取文字识别对象实例
        Tesseract tesseract = TessRactFactory.getTesseract();
        //获取文字列表
        List<Word> words=tesseract.getWords(img.getBufferedImage(), ITessAPI.TessPageIteratorLevel.RIL_SYMBOL);
//        //回收tesseract
//        TessRactFactory.recycling(tesseract);
        //封装到Blocks中
        Blocks blocks = wordsToBlocks(words);
        blocks.setDocImgHeight(img.getBufferedImage().getHeight());
        blocks.setDocImgWidth(img.getBufferedImage().getWidth());
        logger.info("图像宽高:"+img.getBufferedImage().getWidth()+"--"+img.getBufferedImage().getHeight());



        //生成文档

        File file=new File(outPutDocDir.getAbsolutePath()+"/"+date+".docx");
        DocumentCreator creator = new DocumentCreator(blocks,file);
        creator.createWord();
        return FileUtil.getBytes(file);
    }

    /**
     * 将words封装到Blocks中
     * @param words Word列表
     * @return Blocks model.Blocks
     */
    private Blocks wordsToBlocks(List<Word> words) {
        if(words!=null && words.size()>0){
            Blocks blocks = new Blocks();
            for (int i = 0;i<words.size();i++) {
                Word word = words.get(i);
                TextBlock textBlock = new TextBlock(i,new MyRect(word.getBoundingBox()),word.getText(),null,0,word.getConfidence());
                blocks.addTextBlock(textBlock);
            }
            return blocks;
        }
        return null;
    }
}
